<template>
  <Teleport to="body">
    <transition-group
      tag="div"
      class="toast-container"
      enter-active-class="animate__animated animate__fadeInDown animate__faster"
      leave-active-class="animate__animated animate__fadeOutUp animate__faster"
    >
      <div
        v-for="toast in toasts"
        :key="toast.id"
        :class="['toast', `toast-${toast.type}`]"
        style="-webkit-app-region: no-drag"
      >
        <!-- 图标已移除 -->
        <div class="toast-content">
          <div v-if="toast.title" class="toast-title">{{ toast.title }}</div>
          <div class="toast-message">{{ toast.message }}</div>
        </div>
        <button
          class="toast-close"
          :class="{ 'animate__animated animate__pulse': hoveredButton === toast.id }"
          type="button"
          aria-label="关闭"
          @click.stop="handleCloseClick(toast.id, $event)"
          @mouseenter="hoveredButton = toast.id"
          @mouseleave="hoveredButton = null"
        >
          <svg
            width="16"
            height="16"
            viewBox="0 0 24 24"
            fill="none"
            stroke="currentColor"
            stroke-width="2"
            stroke-linecap="round"
            stroke-linejoin="round"
          >
            <line x1="18" y1="6" x2="6" y2="18"></line>
            <line x1="6" y1="6" x2="18" y2="18"></line>
          </svg>
        </button>
      </div>
    </transition-group>
  </Teleport>
</template>

<script setup lang="ts">
import { ref, onBeforeUnmount } from 'vue'
import { ToastOptions } from './index'

export interface Toast extends ToastOptions {
  id: number
}

// 存储所有激活的 Toast
const toasts = ref<Toast[]>([])

// 存储当前悬停的按钮ID
const hoveredButton = ref<number | null>(null)

// 存储定时器以便清理
const timerIds: Record<number, number> = {}

// 生成唯一ID
let toastIdCounter = 0

const createToast = (options: ToastOptions): void => {
  const id = ++toastIdCounter

  // 默认值
  const toast: Toast = {
    id,
    message: options.message,
    title: options.title || '',
    type: options.type || 'info',
    duration: options.duration === undefined ? 3000 : options.duration,
    showIcon: options.showIcon === true // 默认不显示图标
  }

  toasts.value.push(toast)

  // 如果指定了持续时间，则设置自动移除的定时器
  if (toast.duration && toast.duration > 0) {
    timerIds[id] = window.setTimeout(() => {
      removeToast(id)
    }, toast.duration)
  }
}

const removeToast = (id: number): void => {
  const index = toasts.value.findIndex((t) => t.id === id)

  if (index !== -1) {
    // 清除定时器
    if (timerIds[id]) {
      clearTimeout(timerIds[id])
      delete timerIds[id]
    }

    // 从数组中删除
    toasts.value.splice(index, 1)
  }
}

// 处理关闭按钮点击
const handleCloseClick = (id: number, event?: MouseEvent): void => {
  // 防止事件冒泡
  if (event) {
    event.preventDefault()
    event.stopPropagation()
  }
  // 确保在下一个事件循环中执行，避免 Electron 的事件处理冲突
  setTimeout(() => {
    removeToast(id)
  }, 0)
}

// 清除所有 Toast
const clearAllToasts = (): void => {
  // 清除所有定时器
  Object.keys(timerIds).forEach((id) => {
    clearTimeout(timerIds[parseInt(id)])
    delete timerIds[parseInt(id)]
  })

  // 清空数组
  toasts.value = []
}

// 便捷方法
const success = (message: string, options?: Omit<ToastOptions, 'message' | 'type'>): void => {
  createToast({ ...options, message, type: 'success' })
}

const error = (message: string, options?: Omit<ToastOptions, 'message' | 'type'>): void => {
  createToast({ ...options, message, type: 'error' })
}

const info = (message: string, options?: Omit<ToastOptions, 'message' | 'type'>): void => {
  createToast({ ...options, message, type: 'info' })
}

const warning = (message: string, options?: Omit<ToastOptions, 'message' | 'type'>): void => {
  createToast({ ...options, message, type: 'warning' })
}

// 组件卸载前清理所有定时器
onBeforeUnmount(() => {
  Object.keys(timerIds).forEach((id) => {
    clearTimeout(timerIds[parseInt(id)])
  })
})

// 导出方法供组件实例使用
defineExpose({
  createToast,
  removeToast,
  clearAllToasts,
  success,
  error,
  info,
  warning
})
</script>

<style>
.toast-container {
  position: fixed;
  top: 20px;
  right: 20px;
  width: 320px;
  z-index: 9999;
  display: flex;
  flex-direction: column;
  gap: 12px;
  padding: 0;
  margin: 0;
  overflow: visible;
  pointer-events: none; /* 容器不捕获事件，但子元素可以 */
}

.toast {
  position: relative;
  display: flex;
  align-items: flex-start;
  padding: var(--spacing-medium);
  background-color: var(--background-color-primary, #fff);
  border-radius: var(--border-radius-base, 8px);
  box-shadow:
    0 6px 16px rgba(0, 0, 0, 0.08),
    0 0 1px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  pointer-events: auto;
  max-width: 100%;
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.18);
  will-change: transform, opacity;
  transform-origin: top;
  backface-visibility: hidden;
  -webkit-font-smoothing: subpixel-antialiased;
}

.toast-success {
  border-left: 4px solid var(--success-color, #28a745);
  background-color: rgba(40, 167, 69, 0.03);
}

.toast-error {
  border-left: 4px solid var(--error-color, #dc3545);
  background-color: rgba(220, 53, 69, 0.03);
}

.toast-info {
  border-left: 4px solid var(--primary-color, #3370ff);
  background-color: rgba(51, 112, 255, 0.03);
}

.toast-warning {
  border-left: 4px solid var(--warning-color, #ffc107);
  background-color: rgba(255, 193, 7, 0.03);
}

.toast-content {
  flex-grow: 1;
  margin-right: var(--spacing-small);
}

.toast-title {
  font-weight: var(--font-weight-medium, 500);
  margin-bottom: var(--spacing-mini, 4px);
  color: var(--text-color-primary, #333);
  font-size: var(--font-size-base, 14px);
  letter-spacing: 0.01em;
}

.toast-message {
  color: var(--text-color-secondary, #666);
  font-size: var(--font-size-small, 13px);
  line-height: 1.6;
  word-break: break-word;
  letter-spacing: 0.01em;
}

.toast-close {
  flex-shrink: 0;
  width: 32px;
  height: 32px;
  min-width: 32px;
  display: flex;
  justify-content: center;
  align-items: center;
  color: var(--text-color-tertiary, #888);
  cursor: pointer;
  padding: 0;
  margin: 2px 3px 0 0;
  background: transparent;
  border: none;
  outline: none;
  border-radius: 50%;
  z-index: 1000;
  position: relative;
  pointer-events: auto !important;
  -webkit-app-region: no-drag;
  transition: background-color 0.2s ease;
}

.toast-close:hover {
  color: var(--text-color-primary, #333);
  background-color: rgba(0, 0, 0, 0.08);
}

.toast-close:active {
  background-color: rgba(0, 0, 0, 0.12);
}

/* 确保 Animate.css 动画不会被其他样式覆盖 */
.toast-close.animate__animated {
  animation-fill-mode: both !important;
}

/* Animate.css 自定义配置 */
.animate__faster {
  --animate-duration: 0.4s;
}

@media (max-width: 480px) {
  .toast-container {
    width: calc(100% - 40px);
    right: 50%;
    transform: translateX(50%);
  }
}
</style>
